package org.streets.eis.ext.analysis.internal.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.streets.database.Limits;
import org.streets.database.SQLConnection;
import org.streets.database.datadict.DataDict;
import org.streets.database.datadict.TableRelations;
import org.streets.eis.entity.User;
import org.streets.eis.ext.analysis.QuerySet;
import org.streets.eis.ext.analysis.entities.QueryStruct;
import org.streets.eis.ext.analysis.internal.SqlBuilder;
import org.streets.eis.ext.analysis.internal.SqlExtender;
import org.streets.eis.ext.analysis.internal.SqlParser;
import org.streets.eis.ext.analysis.internal.buildlogic.SqlBuilderImpl;
import org.streets.eis.ext.analysis.services.QueryService;

public class QueryServiceImpl implements QueryService {

	private final SQLConnection _connection;
	private final DataDict _dict;
	private final TableRelations _relations;
	private final Logger _logger; 

	public QueryServiceImpl(Logger logger, DataDict dict,TableRelations relations,SQLConnection connection) {
		this._logger = logger;
		this._connection = connection;
		this._dict = dict;
		this._relations = relations;
	}
	
	private List<String> findTitles(QueryStruct struct){
		List<String> list = new ArrayList<String>();
		//TODO:....	
		return list;
	}

	
	public Long count(User user,QueryStruct struct) {
		// TODO Auto-generated method stub
		return null;
	}


	public Long count(User user,String sql) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public QuerySet query(User user,QueryStruct struct,Limits limit) {
		SqlExtender recordPermitExtender = new RecordPermitSqlExtenderImpl(_logger,_dict, _relations,_connection);
		recordPermitExtender.extend(user,struct); 

		SqlExtender fieldPermitExtender = new FieldPermitSqlExtenderImpl(_logger,_dict, _relations,_connection);
		fieldPermitExtender.extend(user,struct); 

		SqlExtender identifierExtender = new IdentifierSqlExtenderImpl(_logger,_dict, _relations,_connection);
		identifierExtender.extend(user,struct);
		
		SqlBuilder sqlBuilder = new SqlBuilderImpl(_logger, _dict, _relations,_connection);
		String sql = sqlBuilder.build(struct);
		
		ResultSet rs = _connection.query(sql,limit);
		
		List<String> titles = findTitles(struct);
		QuerySet qs = new QuerySetImpl(rs,titles,limit);
		
		return qs;
	}


	
	public QuerySet query(User user,String sql,Limits limit){

		SqlParser parser = new SqlParserImpl();
		//SqlStruct struct = parser.parse(sql);
		QueryStruct struct = parser.parse(sql);
		
		return query(user,struct,limit);
	}

	 

}
